package com.cuiweiyou.gimmick;

import java.awt.Color;
import java.awt.Component;
import java.awt.Insets;

import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.table.TableCellRenderer;

public class MulitLineCellRender extends JTextArea implements TableCellRenderer {

    private Color ffffccColor = new Color(Integer.valueOf("#ffffcc".substring(1), 16));
    private Color ccffffColor = new Color(Integer.valueOf("#ccffff".substring(1), 16));

    public MulitLineCellRender() {
        setLineWrap(true);
        setWrapStyleWord(true);
    }

    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected, boolean hasFocus, int row, int column) {
        // 计算当下行的最佳高度
        int maxPreferredHeight = 0;
        for (int i = 0; i < table.getColumnCount(); i++) {
            Object text = table.getValueAt(row, i);
            setText(text + "");
            setSize(table.getColumnModel()
                         .getColumn(column)
                         .getWidth(), 0);
            setMargin(new Insets(2, 5, 1, 5));
            maxPreferredHeight = Math.max(maxPreferredHeight, getPreferredSize().height);
        }

        if (table.getRowHeight(row) != maxPreferredHeight) {
            table.setRowHeight(row, maxPreferredHeight);
        }

        setText(value == null ? "" : value.toString());

        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        if (row % 2 == 0) {
            setBackground(ffffccColor);
        } else if (row % 2 == 1) {
            setBackground(ccffffColor);
        }

        return this;
    }

}